package com.tgy.crud.interceptor;

import com.tgy.crud.domain.User;
import com.tgy.crud.utils.Const;
import com.tgy.crud.utils.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class WebMvcInterceptor implements HandlerInterceptor {

    private RedisTemplate<String,Object> redisTemplate;

    public WebMvcInterceptor(RedisTemplate<String,Object> redisTemplate){

        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info(handler.toString() + "===" + request.getRequestURI());
        if (handler instanceof ResourceHttpRequestHandler){

            return true;
        }

//        redisTemplate.boundValueOps("").set();

        Cookie cookie = Util.getCookie(request, "JSESSIONID");

        if (cookie != null){

            String jessionId = cookie.getValue();

            if (!StringUtils.isEmpty(jessionId)){

                Object user = redisTemplate.opsForValue().get(Util.getJessionId(Const.REDISUSERID, jessionId));

                if (user != null && user instanceof User){

                    request.setAttribute("user",user);
                    return true;
                }
            }
        }

        System.out.println("WebMvcInterceptor:" + request.getRequestURL());
        response.sendRedirect("/tologin");
        return false;
    }


}
